# -*- coding: UTF-8 -*-
"""
@Project :xlx-fastapi
@File    :admin_user_svc.py
@Author  :xlx-ali
@Date    :2024/06/24 13:20 星期一
"""

import json
import time

from fastapi import Request

from app import dao, utils
from app.dao.models import XlxAdmin
from app.service.adminsvc.admin_identity_token import AdminIdentityTokenService
from app.types import apiproto
from app.utils.jwt_util import JwtManageUtil
from app.utils.str_util import StringUtil


class AadminUserService:
    """管理员账号管理服务"""

    @classmethod
    def adminInit(cls) -> utils.HttpResponse:
        pwd_hash = StringUtil.generate_captcha_text()
        admin_md5pwd = StringUtil.makeMd5Password('sfg001', pwd_hash)
        timestamp = int(time.time())
        admin_name = "admin"
        role_id = 1
        admininfo = XlxAdmin(username=admin_name,
                             password=admin_md5pwd,
                             pwd_hash=pwd_hash,
                             role_id=role_id,
                             addtime=timestamp,
                             last_login_time=timestamp,
                             last_login_ip='127.0.0.1',
                             last_login_ipaddress='未知',
                             openid='')
        user = dao.AdminOperateDao.save(admininfo)
        if user:
            msg = f"初始化账号成功,账号：{admin_name},密码：sfg001"
        else:
            msg = "账号初始化失败"
        return utils.ResponseSuccess(msg)
        #  '$admin_name', '$admin_md5pwd', '$pwd_hash', 1, '$timestamp', '$timestamp',

    @classmethod
    def login(cls, postParam: apiproto.AdminUserLoginRequest, request: Request) -> utils.HttpResponse:
        userName = postParam.username
        userInfo = dao.AdminQueryDao.findByUserName(userName)
        if not userInfo:
            return utils.ResponseFail("没有找到用户信息", code=0)
        _password = StringUtil.makeMd5Password(postParam.password, userInfo.pwd_hash)
        if userInfo.password != _password:
            return utils.ResponseFail(code=0, msg="用户名或密码错误")
        if userInfo.status and userInfo.status != 1:
            return utils.ResponseFail(code=0, msg="当前管理员账号已被锁定，请联系超级管理员")
        loginReturn = cls.setLogin(userInfo, request)
        return utils.ResponseSuccess(loginReturn)

    @classmethod
    def setLogin(cls, admininfo: XlxAdmin, request: Request):
        admininfo.last_login_time = int(time.time())
        client_ip = request.headers.get('X-Forwarded-For')
        if client_ip is None:
            client_ip = request.client.host
        admininfo.last_login_ip = client_ip
        admininfo.last_login_ipaddress = StringUtil.get_client_ipaddress(client_ip)
        print("setLogin", client_ip, request.client)
        dao.AdminOperateDao.updataAdmin(admininfo)
        roleinfo = dao.AdminRoleQueryDao.findByid(admininfo.role_id)
        access = roleinfo.access if roleinfo.access == 'all' else json.loads(roleinfo.access)
        access_mobile = roleinfo.access_mobile if roleinfo.access_mobile == 'all' else json.loads(
            roleinfo.access_mobile)
        access_export = 1 if roleinfo.access == 'all' else roleinfo.access_export
        access_delete = 1 if roleinfo.access == 'all' else roleinfo.access_delete
        access_set_service = 1 if roleinfo.access == 'all' else roleinfo.access_set_service
        jwtUtil = JwtManageUtil()
        result = apiproto.AdminUserDetailProto(id=admininfo.id,
                                               username=admininfo.username,
                                               password=admininfo.password,
                                               pwd_hash=admininfo.pwd_hash,
                                               role_id=admininfo.role_id,
                                               addtime=admininfo.addtime,
                                               last_login_time=admininfo.last_login_time,
                                               last_login_ip=admininfo.last_login_ip,
                                               last_login_ipaddress=admininfo.last_login_ipaddress,
                                               openid=admininfo.openid,
                                               is_sc=admininfo.is_sc,
                                               mobile=admininfo.mobile,
                                               status=admininfo.status,
                                               customer_exceed=admininfo.customer_exceed,
                                               avatar=admininfo.avatar)
        token = jwtUtil.generate(result)
        expire = int(StringUtil.webConfig('token_expire'))
        if expire >= 10:
            expire = expire * 60
        else:
            # 默认7天有效期
            expire = 604800
        dao.redis_dao.set(result.id, result.model_dump_json(), expire)
        AdminIdentityTokenService.makeToken(result.id, token)
        # ip = request.client.host
        ip_addr = StringUtil.get_client_ipaddress(client_ip)
        dao.AdminLogOperateDao.writeLog('登录成功', admininfo, client_ip, ip_addr)
        return {'token': token, 'access': access, 'access_export': access_export, 'access_delete': access_delete,
                'access_set_service': access_set_service}
